<?php

namespace app\api\controller\wanlshop;

use addons\wanlshop\library\Decrypt\weixin\wxBizDataCrypt;
use addons\wanlshop\library\WanlChat\WanlChat;
use addons\wanlshop\library\WanlSdk\Common;
use addons\wanlshop\library\WeixinSdk\Mp;
use addons\wanlshop\library\WeixinSdk\Security;
use app\common\controller\Api;
use app\common\library\Sms;

use app\common\model\Perk;
use app\common\model\PerkLog;
use app\common\model\ScanLog;
use app\common\model\user\LevelOrder;
use app\common\model\user\PerkGrant;
use app\common\model\user\RegionLevel;
use fast\Random;
use fast\Http;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Log;
use think\Validate;

/**
 * WanlShop会员接口
 */
class User extends Api
{
    protected $noNeedLogin = ['login', 'logout', 'mobilelogin', 'register', 'resetpwd', 'changeemail', 'changemobile', 'third', 'phone', 'perfect', 'demo'];
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize();
        //WanlChat 即时通讯调用
        $this->wanlchat = new WanlChat();
        $this->auth->setAllowFields(['id', 'username', 'nickname', 'mobile', 'avatar', 'level', 'gender', 'birthday', 'bio', 'money', 'score', 'successions', 'maxsuccessions', 'prevtime', 'logintime', 'loginip', 'jointime']);
    }

    // 调试接口
    public function demo()
    {
    }

    /**
     * 会员登录
     * @ApiMethod   (POST)
     * @param string $account 账号
     * @param string $password 密码
     */
    public function login()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isPost()) {
            $account = $this->request->post('account');
            $password = $this->request->post('password');
            $client_id = $this->request->post('client_id');
            if (!$account || !$password) {
                $this->error(__('Invalid parameters'));
            }
            $ret = $this->auth->login($account, $password);
            if ($ret) {
                if ($client_id) {
                    $this->wanlchat->bind($client_id, $this->auth->id);
                }
                $this->success(__('Logged in successful'), self::userInfo());
            } else {
                $this->error($this->auth->getError());
            }
        }
        $this->error(__('非法请求'));
    }

    /**
     * 手机验证码登录
     * @ApiMethod   (POST)
     * @param string $mobile 手机号
     * @param string $captcha 验证码
     */
    public function mobilelogin()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isPost()) {
            $mobile = $this->request->post('mobile');
            $captcha = $this->request->post('captcha');
            $client_id = $this->request->post('client_id');
            if (!$mobile || !$captcha) {
                $this->error(__('Invalid parameters'));
            }
            if (!Validate::regex($mobile, "^1\d{10}$")) {
                $this->error(__('Mobile is incorrect'));
            }
            /*if (!Sms::check($mobile, $captcha, 'mobilelogin')) {
                $this->error(__('Captcha is incorrect'));
            }*/
            $user = \app\common\model\User::getByMobile($mobile);
            if ($user) {
                if ($user->status != 'normal') {
                    $this->error(__('Account is locked'));
                }
                //如果已经有账号则直接登录
                $ret = $this->auth->direct($user->id);
            } else {
                $ret = $this->auth->register($mobile, Random::alnum(), '', $mobile, []);
            }
            if ($ret) {
                Sms::flush($mobile, 'mobilelogin');
                if ($client_id) {
                    $this->wanlchat->bind($client_id, $this->auth->id);
                }
                $this->success(__('Logged in successful'), self::userInfo());
            } else {
                $this->error($this->auth->getError());
            }
        }
        $this->error(__('非法请求'));
    }

    /**
     * 手机号登录
     * @ApiMethod   (POST)
     * @param string $encryptedData
     * @param string $iv
     */
    public function phone()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isPost()) {
            $post = $this->request->post();
            if (!isset($post['iv'])) {
                $this->error(__('获取手机号异常'));
            }
            if (!isset($post['code'])) {
                $this->error(__('获取手机号异常'));
            }
            // 获取配置
            $config = get_addon_config('wanlshop');
            // 微信小程序一键登录
            $params = [
                'appid' => $config['mp_weixin']['appid'],
                'secret' => $config['mp_weixin']['appsecret'],
                'js_code' => $post['code'],
                'grant_type' => 'authorization_code'
            ];
            $result = Http::sendRequest("https://api.weixin.qq.com/sns/jscode2session", $params, 'GET');
            //$result="{\"session_key\":\"ITGvz5+wrLY4xvqISqbWLQ==\",\"openid\":\"oCYCw63vqn6m3dokM6G9qw9QC1QI\"}";
            $json = (array)json_decode($result['msg'], true);
           // Log::info("openid:".$result['msg']);
            // 判断third是否存在ID,存在快速登录
            if (isset($json['unionid'])) {
                $third = model('app\api\model\wanlshop\Third')->get(['platform' => 'mp_weixin', 'unionid' => $json['unionid']]);
            } else {
                $third = model('app\api\model\wanlshop\Third')->get(['platform' => 'mp_weixin', 'openid' => $json['openid']]);
            }

            if ($third && $third['user_id'] != 0) {
                //如果已经有账号则直接登录
                $ret = $this->auth->direct($third['user_id']);
            } else {
                // 手机号解码
                $decrypt = new wxBizDataCrypt($config['mp_weixin']['appid'], $json['session_key']);
                $decrypt->decryptData($post['encryptedData'], $post['iv'], $data);
                $data = (array)json_decode($data, true);
                // 开始登录
                $mobile = $data['phoneNumber'];
                $user = \app\common\model\User::getByMobile($mobile);
                if ($user) {
                    if ($user->status != 'normal') {
                        $this->error(__('Account is locked'));
                    }
                    //如果已经有账号则直接登录
                    $ret = $this->auth->direct($user->id);
                } else {
                    $ret = $this->auth->register($mobile, Random::alnum(), '', $mobile, []);
                }
            }

            if ($ret) {
                if (isset($post['client_id']) && $post['client_id'] != null) {
                    $this->wanlchat->bind($post['client_id'], $this->auth->id);
                }
                $this->success(__('Logged in successful'), self::userInfo());
            } else {
                $this->error($this->auth->getError());
            }
        }
        $this->error(__('非法请求'));
    }


    /**
     * 注册会员
     * @ApiMethod   (POST)
     * @param string $mobile 手机号
     * @param string $code 验证码
     */
    public function register()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isPost()) {
            $mobile = $this->request->post('mobile');
            $code = $this->request->post('captcha');
            $client_id = $this->request->post('client_id');
            if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
                $this->error(__('Mobile is incorrect'));
            }
            //$ret = Sms::check($mobile, $code, 'register');
            $ret=true;
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            $ret = $this->auth->register($mobile, Random::alnum(), '', $mobile, []);
            if ($ret) {
                if ($client_id) {
                    $this->wanlchat->bind($client_id, $this->auth->id);
                }
                $this->success(__('Sign up successful'), self::userInfo());
            } else {
                $this->error($this->auth->getError());
            }
        }
        $this->error(__('非法请求'));
    }

    /**
     * 注销登录
     */
    public function logout($client_id = null)
    {
        // 踢出即时通讯 1.2.0升级
        foreach ($this->wanlchat->getUidToClientId($this->auth->id) as $client_id) {
            $this->wanlchat->destoryClient($client_id);
        }
        // 退出登录
        $this->auth->logout();
        $this->success(__('Logout successful'));
    }

    /**
     * 修改会员个人信息
     * @ApiMethod   (POST)
     *
     * @param string $avatar 头像地址
     * @param string $username 用户名
     * @param string $nickname 昵称
     * @param string $bio 个人简介
     */
    public function profile()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isPost()) {
            $user = $this->auth->getUser();
            $avatar = $this->request->post('avatar', '', 'trim,strip_tags,htmlspecialchars');
            if ($avatar) {
                $user->avatar = $avatar;
            } else {
                $username = $this->request->post('username');
                $nickname = $this->request->post('nickname');
                $bio = $this->request->post('bio');

                $config = get_addon_config('wanlshop');
                $security = new Security($config['mp_weixin']['appid'], $config['mp_weixin']['appsecret']);
                if ($bio) {
                    $bioCheck = $security->check('msg_sec_check', ['content' => $bio]);
                    if ($bioCheck['code'] !== 0) {
                        if ($bioCheck['code'] === 87014) {
                            $this->error(__('签名包含敏感词汇'));
                        } else {
                            $this->error(__($bioCheck['msg']));
                        }
                    }
                }
                if ($nickname) {
                    $nicknameCheck = $security->check('msg_sec_check', ['content' => $nickname]);
                    if ($nicknameCheck['code'] !== 0) {
                        if ($nicknameCheck['code'] === 87014) {
                            $this->error(__('昵称包含敏感词汇'));
                        } else {
                            $this->error(__($nicknameCheck['msg']));
                        }
                    }
                }
                if ($username) {
                    $usernameCheck = $security->check('msg_sec_check', ['content' => $username]);
                    if ($usernameCheck['code'] !== 0) {
                        if ($usernameCheck['code'] === 87014) {
                            $this->error(__('用户名包含敏感词汇'));
                        } else {
                            $this->error(__($usernameCheck['msg']));
                        }
                    }
                    $exists = \app\common\model\User::where('username', $username)->where('id', '<>', $this->auth->id)->find();
                    if ($exists) {
                        $this->error(__('Username already exists'));
                    }
                    $user->username = $username;
                }
                $user->nickname = $nickname;
                $user->bio = $bio;
            }
            $user->save();
            $this->success('返回成功', $user);
        }
        $this->error(__('非法请求'));
    }

    /**
     * 修改手机号
     * @ApiMethod   (POST)
     * @param string $email 手机号
     * @param string $captcha 验证码
     */
    public function changemobile()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isPost()) {
            $user = $this->auth->getUser();
            $mobile = $this->request->request('mobile');
            $captcha = $this->request->request('captcha');
            if (!$mobile || !$captcha) {
                $this->error(__('Invalid parameters'));
            }
            if (!Validate::regex($mobile, "^1\d{10}$")) {
                $this->error(__('Mobile is incorrect'));
            }
            if (\app\common\model\User::where('mobile', $mobile)->where('id', '<>', $user->id)->find()) {
                $this->error(__('Mobile already exists'));
            }
            $result = Sms::check($mobile, $captcha, 'changemobile');
            if (!$result) {
                $this->error(__('Captcha is incorrect'));
            }
            $verification = $user->verification;
            $verification->mobile = 1;
            $user->verification = $verification;
            $user->mobile = $mobile;
            $user->save();

            Sms::flush($mobile, 'changemobile');
            $this->success();
        }
        $this->error(__('非法请求'));
    }

    /**
     * 重置密码
     * @ApiMethod   (POST)
     * @param string $mobile 手机号
     * @param string $newpassword 新密码
     * @param string $captcha 验证码
     */
    public function resetpwd()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isPost()) {
            $mobile = $this->request->post("mobile");
            $newpassword = $this->request->post("newpassword");
            $captcha = $this->request->post("captcha");
            if (!$newpassword || !$captcha || !$mobile) {
                $this->error(__('Invalid parameters'));
            }
            if (!Validate::regex($mobile, "^1\d{10}$")) {
                $this->error(__('Mobile is incorrect'));
            }
            $user = \app\common\model\User::getByMobile($mobile);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Sms::check($mobile, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Sms::flush($mobile, 'resetpwd');
            //模拟一次登录
            $this->auth->direct($user->id);
            $ret = $this->auth->changepwd($newpassword, '', true);
            if ($ret) {
                $this->success(__('Reset password successful'));
            } else {
                $this->error($this->auth->getError());
            }
        }
        $this->error(__('非法请求'));
    }

    /**
     * 第三方登录-web登录
     * @ApiMethod   (POST)
     * @param string $platform 平台名称
     */
    public function third_web()
    {
        $this->error(__('暂未开放'));
    }


    /**
     * 第三方登录
     * @ApiMethod   (POST)
     * @param string $platform 平台名称
     * @param string $code Code码
     */
    public function third()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isPost()) {
            // 获取登录配置
            $config = get_addon_config('wanlshop');
            // 获取前端参数
            $post = $this->request->post();
            // 登录项目
            $time = time();
            $platform = $post['platform'];
            // 开始登录
            switch ($platform) {
                // 微信小程序登录
                case 'mp_weixin':
                    $params = [
                        'appid' => $config[$platform]['appid'],
                        'secret' => $config[$platform]['appsecret'],
                        'js_code' => $post['loginData']['code'],
                        'grant_type' => 'authorization_code'
                    ];
                    $result = Http::sendRequest("https://api.weixin.qq.com/sns/jscode2session", $params, 'GET');
                    if ($result['ret']) {
                        $json = (array)json_decode($result['msg'], true);
                        if (isset($json['unionid'])) {
                            $third = model('app\api\model\wanlshop\Third')->get(['platform' => 'weixin_open', 'unionid' => $json['unionid']]);
                        } else {
                            $third = model('app\api\model\wanlshop\Third')->get(['platform' => 'weixin_open', 'openid' => $json['openid']]);
                        }
                        // 成功登录
                        if ($third) {
                            $user = model('app\common\model\User')->get($third['user_id']);
                            if (!$user) {
                                $this->success('尚未绑定用户', [
                                    'binding' => 0,
                                    'token' => $third['token']
                                ]);
                            }
                            $third->save([
                                'access_token' => $json['session_key'],
                                'expires_in' => 7776000,
                                'logintime' => $time,
                                'expiretime' => $time + 7776000
                            ]);
                            $ret = $this->auth->direct($user->id);
                            if ($ret) {
                                if (isset($post['client_id']) && $post['client_id'] != null) {
                                    $this->wanlchat->bind($post['client_id'], $this->auth->id);
                                }
                                $this->success(__('Sign up successful'), self::userInfo());
                            } else {
                                $this->error($this->auth->getError());
                            }
                        } else {
                            // 新增$third
                            $third = model('app\api\model\wanlshop\Third');
                            $third->platform = 'weixin_open';
                            if (isset($json['unionid'])) {
                                $third->unionid = $json['unionid'];
                            } else {
                                $third->openid = $json['openid'];
                            }
                            $third->access_token = $json['session_key'];
                            $third->expires_in = 7776000;
                            $third->logintime = $time;
                            $third->expiretime = $time + 7776000;
                            // 判断当前是否登录
                            if ($this->auth->isLogin()) {
                                if (isset($post['client_id']) && $post['client_id'] != null) {
                                    $this->wanlchat->bind($post['client_id'], $this->auth->id);
                                }
                                $third->user_id = $this->auth->id;
                                $third->save();
                                // 直接绑定自动完成
                                $this->success('绑定成功', [
                                    'binding' => 1
                                ]);
                            } else {
                                $third->token = Random::uuid();
                                $third->save();
                                // 通知客户端绑定
                                $this->success('尚未绑定用户', [
                                    'binding' => 0,
                                    'token' => $third->token
                                ]);
                            }
                        }
                    } else {
                        $this->error('API异常，微信小程序登录失败');
                    }
                    break;

                // 微信App登录
                case 'app_weixin':
                    $params = [
                        'access_token' => $post['loginData']['authResult']['access_token'],
                        'openid' => $post['loginData']['authResult']['openid']
                    ];
                    $result = Http::sendRequest("https://api.weixin.qq.com/sns/userinfo", $params, 'GET');
                    if ($result['ret']) {
                        $json = (array)json_decode($result['msg'], true);
                        if (isset($json['unionid'])) {
                            $third = model('app\api\model\wanlshop\Third')->get(['platform' => 'weixin_open', 'unionid' => $json['unionid']]);
                        } else {
                            $third = model('app\api\model\wanlshop\Third')->get(['platform' => 'weixin_open', 'openid' => $json['openid']]);
                        }
                        // 成功登录
                        if ($third) {
                            $third->save([
                                'access_token' => $post['loginData']['authResult']['access_token'],
                                'refresh_token' => $post['loginData']['authResult']['refresh_token'],
                                'expires_in' => $post['loginData']['authResult']['expires_in'],
                                'logintime' => $time,
                                'expiretime' => $time + $post['loginData']['authResult']['expires_in']
                            ]);
                            $ret = $this->auth->direct($third['user_id']);
                            if ($ret) {
                                if (isset($post['client_id']) && $post['client_id'] != null) {
                                    $this->wanlchat->bind($post['client_id'], $this->auth->id);
                                }
                                $this->success(__('Sign up successful'), self::userInfo());
                            } else {
                                $this->error($this->auth->getError());
                            }
                        } else {
                            // 新增$third
                            $third = model('app\api\model\wanlshop\Third');
                            $third->platform = 'weixin_open';
                            if (isset($json['unionid'])) {
                                $third->unionid = $json['unionid'];
                            } else {
                                $third->openid = $json['openid'];
                            }
                            $third->access_token = $post['loginData']['authResult']['access_token'];
                            $third->refresh_token = $post['loginData']['authResult']['refresh_token'];
                            $third->expires_in = $post['loginData']['authResult']['expires_in'];
                            $third->logintime = $time;
                            $third->expiretime = $time + $post['loginData']['authResult']['expires_in'];
                            // 判断当前是否登录,否则注册
                            if ($this->auth->isLogin()) {
                                if (isset($post['client_id']) && $post['client_id'] != null) {
                                    $this->wanlchat->bind($post['client_id'], $this->auth->id);
                                }
                                $third->user_id = $this->auth->id;
                                $third->save();
                                // 直接绑定自动完成
                                $this->success('绑定成功', [
                                    'binding' => 1
                                ]);
                            } else {
                                $username = $json['nickname'];
                                $auth = [];
                                $mobile = '';
                                $gender = $json['sex'] == 1 ? 1 : 0;
                                $avatar = $json['headimgurl'];
                                // 1.1.3升级
                                if (isset($json['unionid'])) {
                                    // 1.1.3升级 查询其他unionid的user_id进行登录
                                    $unionid = model('app\api\model\wanlshop\Third')
                                        ->where('user_id', '<>', 0)
                                        ->where('unionid', '=', $json['unionid'])
                                        ->find();
                                    if ($unionid) {
                                        $auth = $this->auth->direct($unionid['user_id']);
                                    } else {
                                        // 注册账户
                                        $auth = $this->auth->register('u_' . Random::alnum(6), Random::alnum(), '', $mobile, [
                                            'gender' => $gender,
                                            'nickname' => $username,
                                            'avatar' => $avatar
                                        ]);
                                    }
                                } else {
                                    // 注册账户
                                    $auth = $this->auth->register('u_' . Random::alnum(6), Random::alnum(), '', $mobile, [
                                        'gender' => $gender,
                                        'nickname' => $username,
                                        'avatar' => $avatar
                                    ]);
                                }
                                if ($auth) {
                                    if (isset($post['client_id']) && $post['client_id'] != null) {
                                        $this->wanlchat->bind($post['client_id'], $this->auth->id);
                                    }
                                    // 更新第三方登录
                                    $third->user_id = $this->auth->id;
                                    $third->openname = $username;
                                    $third->save();
                                    $this->success(__('Sign up successful'), self::userInfo());
                                } else {
                                    $this->error($this->auth->getError());
                                }
                            }
                        }
                    } else {
                        $this->error('API异常，App登录失败');
                    }
                    break;
                // 微信公众号登录
                case 'h5_weixin':
                    $params = [
                        'appid' => $config['sdk_qq']['gz_appid'],
                        'secret' => $config['sdk_qq']['gz_secret'],
                        'code' => $post['code'],
                        'grant_type' => 'authorization_code'
                    ];
                    $result = Http::sendRequest('https://api.weixin.qq.com/sns/oauth2/access_token', $params, 'GET');
                    if ($result['ret']) {
                        $access = (array)json_decode($result['msg'], true);
                        //获取用户信息
                        $queryarr = [
                            "access_token" => $access['access_token'],
                            "openid" => $access['openid']
                        ];
                        $ret = Http::sendRequest("https://api.weixin.qq.com/sns/userinfo", $queryarr, 'GET');
                        if ($ret['ret']) {
                            $json = (array)json_decode($ret['msg'], true);
                            if (isset($json['unionid'])) {
                                $third = model('app\api\model\wanlshop\Third')->get(['platform' => 'weixin_h5', 'unionid' => $json['unionid']]);
                            } else {
                                $third = model('app\api\model\wanlshop\Third')->get(['platform' => 'weixin_h5', 'openid' => $json['openid']]);
                            }
                            // 成功登录
                            if ($third) {
                                $third->save([
                                    'openid' => $json['openid'], // 1.1.2升级
                                    'access_token' => $access['access_token'],
                                    'refresh_token' => $access['refresh_token'],
                                    'expires_in' => $access['expires_in'],
                                    'logintime' => $time,
                                    'expiretime' => $time + $access['expires_in']
                                ]);
                                // 登录客户端
                                $ret = $this->auth->direct($third['user_id']);
                                if ($ret) {
                                    if (isset($post['client_id']) && $post['client_id'] != null) {
                                        $this->wanlchat->bind($post['client_id'], $this->auth->id);
                                    }
                                    $this->success(__('Sign up successful'), self::userInfo());
                                } else {
                                    $this->error($this->auth->getError());
                                }
                            } else {
                                // 新增$third
                                $third = model('app\api\model\wanlshop\Third');
                                $third->platform = 'weixin_h5';
                                // 1.1.2升级
                                if (isset($json['unionid'])) {
                                    $third->unionid = $json['unionid'];
                                    $third->openid = $json['openid'];
                                } else {
                                    $third->openid = $json['openid'];
                                }
                                $third->access_token = $access['access_token'];
                                $third->refresh_token = $access['refresh_token'];
                                $third->expires_in = $access['expires_in'];
                                $third->logintime = $time;
                                $third->expiretime = $time + $access['expires_in'];
                                // 获取到的用户信息
                                $username = $json['nickname'];
                                $auth = [];
                                $mobile = '';
                                $gender = $json['sex'] == 1 ? 1 : 0;
                                $avatar = $json['headimgurl'];

                                // 1.1.3升级
                                if (isset($json['unionid'])) {
                                    // 1.1.3升级 查询其他unionid的user_id进行登录
                                    $unionid = model('app\api\model\wanlshop\Third')
                                        ->where('user_id', '<>', 0)
                                        ->where('unionid', '=', $json['unionid'])
                                        ->find();

                                    if ($unionid) {
                                        $auth = $this->auth->direct($unionid['user_id']);
                                    } else {
                                        // 注册账户
                                        $auth = $this->auth->register('u_' . Random::alnum(6), Random::alnum(), '', $mobile, [
                                            'gender' => $gender,
                                            'nickname' => $username,
                                            'avatar' => $avatar
                                        ]);
                                    }
                                } else {
                                    // 注册账户
                                    $auth = $this->auth->register('u_' . Random::alnum(6), Random::alnum(), '', $mobile, [
                                        'gender' => $gender,
                                        'nickname' => $username,
                                        'avatar' => $avatar
                                    ]);
                                }

                                if ($auth) {
                                    if (isset($post['client_id']) && $post['client_id'] != null) {
                                        $this->wanlchat->bind($post['client_id'], $this->auth->id);
                                    }
                                    // 更新第三方登录
                                    $third->user_id = $this->auth->id;
                                    $third->openname = $username;
                                    $third->save();
                                    $this->success(__('Sign up successful'), self::userInfo());
                                } else {
                                    $this->error($this->auth->getError());
                                }
                            }
                        } else {
                            $this->error('获取用户信息失败！');
                        }
                    } else {
                        $this->error('获取openid失败！');
                    }
                    break;
                // QQ小程序登录
                case 'mp_qq':
                    $params = [
                        'appid' => $config[$platform]['appid'],
                        'secret' => $config[$platform]['appsecret'],
                        'js_code' => $post['loginData']['code'],
                        'grant_type' => 'authorization_code'
                    ];
                    $result = Http::sendRequest("https://api.q.qq.com/sns/jscode2session", $params, 'GET');
                    if ($result['ret']) {
                        $json = (array)json_decode($result['msg'], true);
                        if (isset($json['unionid'])) {
                            $third = model('app\api\model\wanlshop\Third')->get(['platform' => 'qq_open', 'unionid' => $json['unionid']]);
                        } else {
                            $third = model('app\api\model\wanlshop\Third')->get(['platform' => 'qq_open', 'openid' => $json['openid']]);
                        }
                        // 成功登录
                        if ($third) {
                            $user = model('app\common\model\User')->get($third['user_id']);
                            if (!$user) {
                                $this->success('尚未绑定用户', [
                                    'binding' => 0,
                                    'token' => $third['token']
                                ]);
                            }
                            $third->save([
                                'access_token' => $json['session_key'],
                                'expires_in' => 7776000,
                                'logintime' => $time,
                                'expiretime' => $time + 7776000
                            ]);
                            $ret = $this->auth->direct($user->id);
                            if ($ret) {
                                if (isset($post['client_id']) && $post['client_id'] != null) {
                                    $this->wanlchat->bind($post['client_id'], $this->auth->id);
                                }
                                $this->success(__('Sign up successful'), self::userInfo());
                            } else {
                                $this->error($this->auth->getError());
                            }
                        } else {
                            // 新增$third
                            $third = model('app\api\model\wanlshop\Third');
                            $third->platform = 'qq_open';
                            if (isset($json['unionid'])) {
                                $third->unionid = $json['unionid'];
                            } else {
                                $third->openid = $json['openid'];
                            }
                            $third->access_token = $json['session_key'];
                            $third->expires_in = 7776000;
                            $third->logintime = $time;
                            $third->expiretime = $time + 7776000;
                            // 判断当前是否登录
                            if ($this->auth->isLogin()) {
                                // 1.1.4升级
                                if (isset($post['client_id']) && $post['client_id'] != null) {
                                    $this->wanlchat->bind($post['client_id'], $this->auth->id);
                                }
                                $third->user_id = $this->auth->id;
                                $third->save();
                                // 直接绑定自动完成
                                $this->success('绑定成功', [
                                    'binding' => 1
                                ]);
                            } else {
                                $third->token = Random::uuid();
                                $third->save();
                                // 通知客户端绑定
                                $this->success('尚未绑定用户', [
                                    'binding' => 0,
                                    'token' => $third->token
                                ]);
                            }
                        }
                    } else {
                        $this->error('API异常，微信小程序登录失败');
                    }
                    break;

                // QQ App登录
                case 'app_qq':
                    $params = [
                        'access_token' => $post['loginData']['authResult']['access_token']
                    ];
                    $options = [
                        CURLOPT_HTTPHEADER => [
                            'Content-Type: application/x-www-form-urlencoded'
                        ]
                    ];
                    $result = Http::sendRequest("https://graph.qq.com/oauth2.0/me", $params, 'GET', $options);
                    if ($result['ret']) {
                        $json = (array)json_decode(str_replace(" );", "", str_replace("callback( ", "", $result['msg'])), true);
                        if ($json['openid'] == $post['loginData']['authResult']['openid']) {
                            $third = model('app\api\model\wanlshop\Third')->get(['platform' => 'qq_open', 'openid' => $json['openid']]);
                            if ($third) {
                                $user = model('app\common\model\User')->get($third['user_id']);
                                if (!$user) {
                                    $this->success('尚未绑定用户', [
                                        'binding' => 0,
                                        'token' => $third['token']
                                    ]);
                                }
                                $third->save([
                                    'access_token' => $post['loginData']['authResult']['access_token'],
                                    'expires_in' => $post['loginData']['authResult']['expires_in'],
                                    'logintime' => $time,
                                    'expiretime' => $time + $post['loginData']['authResult']['expires_in']
                                ]);
                                $ret = $this->auth->direct($third['user_id']);
                                if ($ret) {
                                    if (isset($post['client_id']) && $post['client_id'] != null) {
                                        $this->wanlchat->bind($post['client_id'], $this->auth->id);
                                    }
                                    $this->success(__('Sign up successful'), self::userInfo());
                                } else {
                                    $this->error($this->auth->getError());
                                }
                            } else {
                                // 新增$third
                                $third = model('app\api\model\wanlshop\Third');
                                $third->platform = 'qq_open';
                                $third->openid = $json['openid'];
                                $third->access_token = $post['loginData']['authResult']['access_token'];
                                $third->expires_in = $post['loginData']['authResult']['expires_in'];
                                $third->logintime = $time;
                                $third->expiretime = $time + $post['loginData']['authResult']['expires_in'];
                                // 判断当前是否登录
                                if ($this->auth->isLogin()) {
                                    if (isset($post['client_id']) && $post['client_id'] != null) {
                                        $this->wanlchat->bind($post['client_id'], $this->auth->id);
                                    }
                                    $third->user_id = $this->auth->id;
                                    $third->save();
                                    // 直接绑定自动完成
                                    $this->success('绑定成功', [
                                        'binding' => 1
                                    ]);
                                } else {
                                    $third->token = Random::uuid();
                                    $third->save();
                                    // 通知客户端绑定
                                    $this->success('尚未绑定用户', [
                                        'binding' => 0,
                                        'token' => $third->token
                                    ]);
                                }
                            }
                        } else {
                            $this->error(__('非法请求，机器信息已提交'));
                        }
                    } else {
                        $this->error('API异常，App登录失败');
                    }
                    break;
                // QQ 网页登录
                case 'h5_qq':
                    // 后续版本上线
                    break;
                // 微博App登录
                case 'app_weibo':
                    $params = [
                        'access_token' => $post['loginData']['authResult']['access_token']
                    ];
                    $options = [
                        CURLOPT_HTTPHEADER => [
                            'Content-Type: application/x-www-form-urlencoded'
                        ],
                        CURLOPT_POSTFIELDS => http_build_query($params),
                        CURLOPT_POST => 1
                    ];
                    $result = Http::post("https://api.weibo.com/oauth2/get_token_info", $params, $options);
                    $json = (array)json_decode($result, true);
                    if ($json['uid'] == $post['loginData']['authResult']['uid']) {
                        $third = model('app\api\model\wanlshop\Third')->get(['platform' => 'weibo_open', 'openid' => $json['uid']]);
                        if ($third) {
                            $user = model('app\common\model\User')->get($third['user_id']);
                            if (!$user) {
                                $this->success('尚未绑定用户', [
                                    'binding' => 0,
                                    'token' => $third['token']
                                ]);
                            }
                            $third->save([
                                'access_token' => $post['loginData']['authResult']['access_token'],
                                'expires_in' => $json['expire_in'],
                                'logintime' => $json['create_at'],
                                'expiretime' => $json['create_at'] + $json['expire_in']
                            ]);
                            $ret = $this->auth->direct($third['user_id']);
                            if ($ret) {
                                if (isset($post['client_id']) && $post['client_id'] != null) {
                                    $this->wanlchat->bind($post['client_id'], $this->auth->id);
                                }
                                $this->success(__('Sign up successful'), self::userInfo());
                            } else {
                                $this->error($this->auth->getError());
                            }
                        } else {
                            // 新增$third
                            $third = model('app\api\model\wanlshop\Third');
                            $third->platform = 'weibo_open';
                            $third->openid = $json['uid'];
                            $third->access_token = $post['loginData']['authResult']['access_token'];
                            $third->expires_in = $json['expire_in'];
                            $third->logintime = $json['create_at'];
                            $third->expiretime = $json['create_at'] + $json['expire_in'];
                            // 判断当前是否登录
                            if ($this->auth->isLogin()) {
                                // 1.1.4升级
                                if (isset($post['client_id']) && $post['client_id'] != null) {
                                    $this->wanlchat->bind($post['client_id'], $this->auth->id);
                                }
                                $third->user_id = $this->auth->id;
                                $third->save();
                                // 直接绑定自动完成
                                $this->success('绑定成功', [
                                    'binding' => 1
                                ]);
                            } else {
                                $third->token = Random::uuid();
                                $third->save();
                                // 通知客户端绑定
                                $this->success('尚未绑定用户', [
                                    'binding' => 0,
                                    'token' => $third->token
                                ]);
                            }
                        }
                    } else {
                        $this->error(__('非法请求，机器信息已提交'));
                    }
                    break;

                // 小米App登录
                case 'app_xiaomi':

                    break;

                // 苹果登录
                case 'apple':
                    // 后续版本上线
                    break;
                default:
                    $this->error('暂并不支持此方法登录');
            }
        }
        $this->error(__('10086非正常请求'));
    }

    /**
     * 进一步完善资料
     * @ApiMethod   (POST)
     */
    public function perfect()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isPost()) {
            $post = $this->request->post();
            // 判断token没有绑定 1.1.4升级
            $third = model('app\api\model\wanlshop\Third')
                ->where('token', '=', $post['token'])
                ->find();
            // 当user_id 不为空可以绑定
            if ($third['user_id'] == 0 && $third) {
                $username = $post['nickName'];
                $auth = [];
                $mobile = '';
                $gender = $post['gender'];
                $avatar = $post['avatarUrl'];
                // 1.1.4升级
                if ($third['unionid']) {
                    // 1.1.3升级 查询其他unionid的user_id进行登录
                    $unionid = model('app\api\model\wanlshop\Third')
                        ->where('id', '<>', $third['id'])
                        ->where('unionid', '=', $third['unionid'])
                        ->find();
                    if ($unionid) {
                        $auth = $this->auth->direct($unionid['user_id']);
                    } else {
                        $auth = $this->auth->register('u_' . Random::alnum(6), Random::alnum(), '', $mobile, [
                            'gender' => $gender,
                            'nickname' => $username,
                            'avatar' => $avatar
                        ]);
                    }
                } else {
                    $auth = $this->auth->register('u_' . Random::alnum(6), Random::alnum(), '', $mobile, [
                        'gender' => $gender,
                        'nickname' => $username,
                        'avatar' => $avatar
                    ]);
                }
                if ($auth) {
                    // 1.1.4升级
                    if (isset($post['client_id']) && $post['client_id'] != null) {
                        $this->wanlchat->bind($post['client_id'], $this->auth->id);
                    }
                    // 更新第三方登录
                    $third->save([
                        'user_id' => $this->auth->id,
                        'openname' => $username
                    ]);
                    $this->success(__('Sign up successful'), self::userInfo());
                } else {
                    $this->error($this->auth->getError());
                }
            } else {
                $this->error(__('非法请求，机器信息已提交'));
            }
        }
        $this->error(__('非法请求'));
    }

    /**
     * 刷新用户中心
     * @ApiMethod   (POST)
     */
    public function refresh()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isPost()) {
            $this->success(__('刷新成功'), self::userInfo());
        }
        $this->error(__('非法请求'));
    }
//生成分享海报
    public function getPoster($user_id)
    {
        $text="https://".$_SERVER['HTTP_HOST']."?team_id=".$user_id;//推广店铺
        $qrCode = \addons\qrcode\library\Service::qrcode(["text"=>$text]);
        $qrcodePath = ROOT_PATH . 'public/uploads/team_code/';
        $url="/uploads/team_code/";
        // 写入到文件
        if (!is_dir($qrcodePath)) {
            @mkdir($qrcodePath);
        }
        $name=md5("id".$user_id);
        $config = get_addon_config('qrcode');
        if (is_really_writable($qrcodePath)) {
            $filePath = $qrcodePath  .$name. '.' . $config['format'];
            $qrCode->writeFile($filePath);
        }
        $url.=$name. '.' . $config['format'];
        $background = "http://".$_SERVER['HTTP_HOST']. '/static/index/team.jpg';
        $code_url = "http://".$_SERVER['HTTP_HOST'].$url;
        $config = array(
            'image' => array(
                array(
                    'url' => $code_url,     //二维码地址
                    'is_yuan' => false,          //true图片圆形处理
                    'stream' => 0,
                    'left' => -1,               //小于0为小平居中
                    'top' => 280,
                    'right' => 0,
                    'width' => 420,             //图像宽
                    'height' => 420,            //图像高
                    'opacity' => 100            //透明度
                ),
            ),
            'text' => array(
                array(
                    'text'=>'',
                    'left'=>-1,
                    'top'=>1625,
                    'fontPath'=>'./assets/fonts/verdana.ttf',     //字体文件
                    'fontSize'=>28,             //字号
                    'fontColor'=>'0,0,0',       //字体颜色
                    'angle'=>0, //转换角度
                ),
            ),
            'background' => $background,//config("site.share_image")?config("site.share_image"):cdnurl('/uploads/20220517/image1.jpg',true),//cdnurl('/uploads/20220517/image1.jpg',true),          //背景图
        );

        $fileUrl = '/uploads/team_code/share/' .$name . '.jpg';
        $filename = ROOT_PATH . 'public' . $fileUrl;
        $path = "./uploads/team_code/share" ;
        if (!is_dir($path)) {
            @mkdir($path, 0755, true);
        }
        //echo createPoster($config);
        //$filename为空是真接浏览器显示图片
        $this->createPoster($config, $filename);
        return $fileUrl;
    }
    /**
     * 生成宣传海报
     * @param array  参数,包括图片和文字
     * @param string $filename 生成海报文件名,不传此参数则不生成文件,直接输出图片
     * @return [type] [description]
     */
    function createPoster($config = array(), $filename = "")
    {
        //如果要看报什么错，可以先注释调这个header
        //if(empty($filename)) header("content-type: image/png");
        if (empty($filename)) header("content-type: image/png");
        $imageDefault = array(
            'left' => 0,
            'top' => 0,
            'right' => 0,
            'bottom' => 0,
            'width' => 100,
            'height' => 100,
            'opacity' => 100
        );
        $textDefault = array(
            'text' => '',
            'left' => 0,
            'top' => 0,
            'fontSize' => 32, //字号
            'fontColor' => '255,255,255', //字体颜色
            'angle' => 0,
        );
        $background = $config['background']; //海报最底层得背景
        //背景方法
        $backgroundInfo = getimagesize($background);
        $backgroundFun = 'imagecreatefrom' . image_type_to_extension($backgroundInfo[2], false);
        $background = $backgroundFun($background);
        $backgroundWidth = imagesx($background); //背景宽度
        $backgroundHeight = imagesy($background); //背景高度
        $imageRes = imageCreatetruecolor($backgroundWidth, $backgroundHeight);
        $color = imagecolorallocate($imageRes, 0, 0, 0);
        imagefill($imageRes, 0, 0, $color);
        imagecopyresampled($imageRes, $background, 0, 0, 0, 0, imagesx($background), imagesy($background), imagesx($background), imagesy($background));
        //处理了图片
        if (!empty($config['image'])) {
            foreach ($config['image'] as $key => $val) {
                $val = array_merge($imageDefault, $val);
                $info = getimagesize($val['url']);
                $function = 'imagecreatefrom' . image_type_to_extension($info[2], false);
                if ($val['stream']) { //如果传的是字符串图像流
                    $info = getimagesizefromstring($val['url']);
                    $function = 'imagecreatefromstring';
                }
                $res = $function($val['url']);
                $resWidth = $info[0];
                $resHeight = $info[1];
                //建立画板 ，缩放图片至指定尺寸
                $canvas = imagecreatetruecolor($val['width'], $val['height']);
                imagefill($canvas, 0, 0, $color);
                //如果是透明的gif或png做透明处理
                $ext = pathinfo($val['url']);
                if (array_key_exists('extension', $ext)) {
                    if ($ext['extension'] == 'gif' || $ext['extension'] == 'png') {
                        // imageColorTransparent($canvas, $color); //颜色透明
                    }
                }
                //关键函数，参数（目标资源，源，目标资源的开始坐标x,y, 源资源的开始坐标x,y,目标资源的宽高w,h,源资源的宽高w,h）
                imagecopyresampled($canvas, $res, 0, 0, 0, 0, $val['width'], $val['height'], $resWidth, $resHeight);
                //$val['left'] = $val['left']<0?$backgroundWidth- abs($val['left']) - $val['width']:$val['left'];
                //如果left小于-1我这做成了计算让其水平居中
                if ($val['left'] < 0) {
                    $val['left'] = ceil($backgroundWidth - $val['width']) / 2;
                }
                $val['top'] = $val['top'] < 0 ? $backgroundHeight - abs($val['top']) - $val['height'] : $val['top'];
                //放置图像
                imagecopymerge($imageRes, $canvas, $val['left'], $val['top'], $val['right'], $val['bottom'], $val['width'], $val['height'], $val['opacity']); //左，上，右，下，宽度，高度，透明度

            }
        }
        //处理文字
        if (!empty($config['text'])) {
            foreach ($config['text'] as $key => $val) {
                $val = array_merge($textDefault, $val);
                list($R, $G, $B) = explode(',', $val['fontColor']);
                $fontColor = imagecolorallocate($imageRes, $R, $G, $B);
                //$val['left'] = $val['left']<0?$backgroundWidth- abs($val['left']):$val['left'];
                //如果left小于-1我这做成了计算让其水平居中
                if ($val['left'] < 0) {
                    $fontBox = imagettfbbox($val['fontSize'], 0, $val['fontPath'], $val['text']); //文字水平居中实质
                    $val['left'] = ceil(($backgroundWidth - $fontBox[2]) / 2); //计算文字的水平位置

                }
                $val['top'] = $val['top'] < 0 ? $backgroundHeight - abs($val['top']) : $val['top'];
                imagettftext($imageRes, $val['fontSize'], $val['angle'], $val['left'], $val['top'], $fontColor, $val['fontPath'], $val['text']);
            }
            /*foreach ($config['text'] as $key => $val) {
                $val = array_merge($textDefault,$val);
                list($R,$G,$B) = explode(',', $val['fontColor']);
                $fontColor = imagecolorallocate($imageRes, $R, $G, $B);
                $val['left'] = $val['left']<0?$backgroundWidth- abs($val['left']):$val['left'];
                $val['top'] = $val['top']<0?$backgroundHeight- abs($val['top']):$val['top'];
                imagettftext($imageRes,$val['fontSize'],$val['angle'],$val['left'],$val['top'],$fontColor,$val['fontPath'],$val['text']);
            }*/
        }
        //生成图片
        if (!empty($filename)) {
            $res = imagejpeg($imageRes, $filename, 90); //保存到本地
            imagedestroy($imageRes);
            if (!$res) return false;
            return $filename;
        } else {
            return $imageRes;
            header("Content-type:image/png");
            imagejpeg($imageRes); //在浏览器上显示
            imagedestroy($imageRes);
        }
    }
    /**
     * 数据统计 - 内部使用，开发者不要调用
     */
    private function userInfo()
    {
        $user_id = $this->auth->id;
        // 查询订单
        $order = model('app\api\model\wanlshop\Order')
            ->where('user_id', $user_id)
            ->select();
        $orderCount = array_count_values(array_column($order, 'state'));

        // 物流列表
        $logistics = [];
        foreach ($order as $value) {
            if ($value['state'] >= 3 && $value['state'] <= 6) {
                //需要查询的订单
            }
        }
        // 统计数量
        $collection = [];
        $concern = [];
        // 1.1.0升级
        $footgoodsprint = [];
        $footgroupsprint = [];
        foreach (model('app\api\model\wanlshop\GoodsFollow')->where('user_id', $user_id)->select() as $row) {
            if ($row['goods_type'] === 'goods') {
                if (model('app\api\model\wanlshop\Goods')->get($row['goods_id'])) {
                    $collection[] = $row['id'];
                }
            } else if ($row['goods_type'] === 'groups') {
                if (model('app\api\model\wanlshop\groups\Goods')->get($row['goods_id'])) {
                    $collection[] = $row['id'];
                }
            }
        }
        // 1.0.8升级  通过uuid查询足迹
        $uuid = $this->request->server('HTTP_UUID');
        if (!isset($uuid)) {
            $charid = strtoupper(md5($this->request->header('user-agent') . $this->request->ip()));
            $uuid = substr($charid, 0, 8) . chr(45) . substr($charid, 8, 4) . chr(45) . substr($charid, 12, 4) . chr(45) . substr($charid, 16, 4) . chr(45) . substr($charid, 20, 12);
        }
        foreach (model('app\api\model\wanlshop\Record')->where('uuid', $uuid)->select() as $row) {
            if ($row['goods_type'] === 'goods') {
                if (model('app\api\model\wanlshop\Goods')->get($row['goods_id'])) {
                    $footgoodsprint[] = $row['goods_id'];
                }
            } else if ($row['goods_type'] === 'groups') {
                if (model('app\api\model\wanlshop\groups\Goods')->get($row['goods_id'])) {
                    $footgroupsprint[] = $row['goods_id'];
                }
            }
        }

        // 查询动态 、收藏夹、关注店铺、足迹、红包卡券
        $finish = isset($orderCount[6]) ? $orderCount[6] : 0;
        $pay = isset($orderCount[1]) ? $orderCount[1] : 0;
        $delive = isset($orderCount[2]) ? $orderCount[2] : 0;
        $receiving = isset($orderCount[3]) ? $orderCount[3] : 0;
        $evaluate = isset($orderCount[4]) ? $orderCount[4] : 0;
        // 订单状态:1=待支付,2=待成团,3=待发货,4=待收货,5=待评论,6=已完成,7=已取消
        $groups = model('app\api\model\wanlshop\groups\Order')
            ->where('user_id', 'eq', $user_id)
            ->where('state', 'neq', 7)
            ->count();
        //lina 新增 start
        $user=$this->auth->getUserinfo();
        if(!empty($user["permanent"])){
            $permanent=json_decode($user["permanent"],true);
            $user["permanent"]=$permanent["formatted_address"].$permanent["address_full"];
        }
        /*$user=model('app\common\model\User')->find(6);*/
        if($user["level_id"]==1 && !empty($user["level_time"]) && !empty($user["level_time"]) && $user["level_time"]<=time()){
            \app\common\model\User::where(["id"=>$user["id"]])->update(["level_id"=>0]);
        }
        $level = model('app\common\model\user\Level')
            ->field("id,name")
            ->where(['id'=>$user["level_id"]])
            ->find();
        if(!empty($level) && $level["id"]==1 && !empty($user["level_time"]))
        {
            $level["level_time"]=date("Y-m-d",$user["level_time"]);
        }
        //现金补贴
        $order=LevelOrder::field("sum(residue_money) value")
            ->where("residue_money > 0 and state='2'")
            ->where(["user_id"=>$user_id,"state"=>'2'])
            ->buildSql();//未发放
        $perk= LevelOrder::field("sum(subsidy_money) value")
            ->where(["user_id"=>$user_id,"state"=>'2'])
            ->union([$order], true)
            ->select();//所有
        //2023-12-18 lina 修改 start
        //现金补贴----后台发放或者完成三返一
        /*$pc_order=PerkGrant::field("sum(residue_money) value")
            ->where("residue_money > 0")
            ->where('FIND_IN_SET("' . $user["id"] . '", user_ids)')
            ->buildSql();//未发放
        $pc_perk= PerkGrant::field("sum(subsidy_money) value")
            ->where('FIND_IN_SET("' . $user["id"] . '", user_ids)')
            ->union([$pc_order], true)
            ->select();//所有*/
        $all_perk_money=bcadd(($perk[0]["value"]??0),($pc_perk[0]["value"]??0),2);
        $not_perk_money=bcadd(($perk[1]["value"]??0),($pc_perk[1]["value"]??0),2);
        $stop_perk_money=bcsub($all_perk_money,$not_perk_money,2)??0;
        //2023-12-18 lina 修改 end
        //$stop_perk_money=bcsub($perk[0]["value"],$perk[1]["value"],2)??0;
        $totalStaff= \app\common\model\User::field("count(1) value")
            ->where(["is_staff"=>1,"team_id"=>$user_id])
            ->buildSql();//员工人数
        $totalStaffall= \app\common\model\User::field("count(1) value")
            ->where(["team_id"=>$user_id])
            ->union([$totalStaff], true)
            ->select();//所有
        if($user["identity"]==1 && empty($user["team_code"])){
            //团长
            $url=$this->getPoster($user_id);
            $user["team_code"]=$url;
            \app\common\model\User::where(["id"=>$user["id"]])->update(["team_code"=>$url]);
        }
        $region_address="";
        $regionLevelName="";
        if($user["identity"]==2)
        {
            //区域合伙人
            if(!empty($user["region_address"])){
                $region_address=model('app\common\model\Area')->field('GROUP_CONCAT(name) name')->whereIn("id",$user["region_address"])->find();
            }
            $regionLevelName=RegionLevel::where(["id"=>$user["region_level_id"]])->column("name")[0]??'';
        }
        //lina 新增 end
        return [
            'userinfo' => $user,
            'statistics' => [
                'dynamic' => [
                    'collection' => count($collection),
                    'concern' => model('app\api\model\wanlshop\find\Follow')->where('user_id', $user_id)->count(),
                    'footprint' => count(array_flip($footgoodsprint)) + count(array_flip($footgroupsprint)),
                    'coupon' => model('app\api\model\wanlshop\CouponReceive')->where(['user_id' => $user_id, 'state' => '1'])->count(),
                    'accountbank' => model('app\api\model\wanlshop\PayAccount')->where('user_id', $user_id)->count()
                ],
                'order' => [
                    'whole' => $finish + $pay + $delive + $receiving + $evaluate,
                    'groups' => $groups,
                    'pay' => $pay,
                    'delive' => $delive,
                    'receiving' => $receiving,
                    'evaluate' => $evaluate,
                    // 1.1.6升级 退款状态:0=申请退款,1=卖家同意,2=卖家拒绝,3=申请平台介入,4=成功退款,5=退款已关闭,6=已提交物流,7=第三方退款中,8=退款失败
                    'customer' => model('app\api\model\wanlshop\Refund')->where(['state' => ['in', '0,1,2,3,6,7,8'], 'user_id' => $this->auth->id])->count()
                ],
                'logistics' => $logistics
            ],
            //lina 新增 start
            'level'=>$level??[],
            'perk'=>[
                "all_perk_money"=>$all_perk_money,//应发放补贴金额
                "not_perk_money"=>$not_perk_money,//未发放补贴金额
                "perk_money"=>$user["perk_money"]??0,//可用补贴金额
                "stop_perk_money"=>$stop_perk_money,//已发放补贴金额
            ],
            'totalStaff'=>$totalStaffall[1]["value"]??0,//员工人数
            'totalStaffAll'=>$totalStaffall[0]["value"]??0,//员工总人数
            'region_address'=>$region_address,//区域合伙人代理区域
            'regionLevelName'=>$regionLevelName,//区域合伙人等级名称
            //lina 新增 end
        ];
    }

    /**
     * 获取评论列表
     *
     * @ApiSummary  (WanlShop 获取我的所有评论)
     * @ApiMethod   (GET)
     *
     * @param string $list_rows 每页数量
     * @param string $page 当前页
     */
    public function comment()
    {
        $list = model('app\api\model\wanlshop\GoodsComment')
            ->where('user_id', $this->auth->id)
            ->field('id,images,score,goods_id,order_goods_id,state,content,createtime')
            ->order('createtime desc')
            ->paginate()
            ->each(function ($data, $key) {
                $data['order_goods'] = $data->order_goods ? $data->order_goods->visible(['id', 'title', 'image', 'price']) : '';
                return $data;
            });
        $this->success('返回成功', $list);
    }

    /**
     * 获取积分明细
     */
    public function scoreLog()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isPost()) {
            $list = model('app\common\model\ScoreLog')
                ->where('user_id', $this->auth->id)
                ->order('createtime desc')
                ->paginate();
            $this->success('ok', $list);
        }
        $this->error(__('非法请求'));
    }

    //新增 lina start

    /**
     *会员等级列表
     * */
    public function levelList()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isGet()) {
            $user = model('app\common\model\User')->find($this->auth->id);//$this->userInfo();
            $list = model('app\common\model\user\Level')
                ->alias("level")
                ->field("id,name,price,subsidy,discount,remark")
                ->with(["goods" => function ($query) {
                    $query->withField('title,image');
                }])
                //->where('level.id', ">", $user["level_id"])
                ->order('level.id asc')
                ->select();
            if(!empty($list)){
                foreach ($list as &$v){
                    $v["light"]=false;
                    if(!empty($user)){
                        $order=LevelOrder::where(["state"=>2,"user_id"=>$user["id"],"level_id"=>$v["id"]])->find();
                        /*if($v["id"]==$user["level_id"]){
                            $v["light"]=true;
                        }*/
                        if(!empty($order)) $v["light"]=true;
                        //体验卡 start
                       /* if($v["id"]==1){
                            if($user["level_time"]<=time()){
                                $v["light"]=false;
                            }
                        }*/
                        //体验卡 end
                    }
                }
            }
            $this->success('ok', $list);
        }
        $this->error(__('非法请求'));
    }

    /**
     * 购买等级
     * */
    public function createLevelOrder()
    {
        if ($this->request->isGet()) {
            $get = $this->request->get();
            $level = model('app\common\model\user\Level')->get($get["id"]);
            if (empty($level)) $this->error(__('等级不存在'));
            $user = $this->auth->getUser();
            if ($user["identity"] == 3 || $user["is_staff"]==1) $this->error(__('员工暂不支持'));
            if ($user["level_id"] == $level["id"]) $this->error(__('该等级已购买'));
            if ($user["level_id"] > $level["id"]) $this->error(__('不允许购买低等级'));
            $user_id = $this->auth->id;
            $address=\app\admin\model\User::field("permanent")->find($user_id)->toArray();
            if(empty($address) || empty($address["permanent"])) $this->error(__('您还没有设置常驻地址哦'));
            //$orderModel = model('app\common\model\LevelOrder');
            $config = get_addon_config('wanlshop');
            $day_radio = $config["subsidy"]["day_radio"] ?? 10;//每日到账比例
            $level["day_radio"] = $day_radio;
            $daily_money = bcmul($level["subsidy"], ($day_radio / 100), 2);

            $agent_id= $get["agent_id"]??0;
            if(empty($agent_id)){
                $scan=ScanLog::where(["user_id"=>$this->auth->id])->order("createtime","desc")->find();
                if(!empty($scan) && !empty($scan["click_id"])){
                    $agent_id=$scan["click_id"];
                }
            }
            $orderModel = new LevelOrder();
            $orderModel->user_id = $user_id;
            $orderModel->level_id = $get["id"];
            $orderModel->order_no = $level["id"] . $this->auth->id;
            $orderModel->level_details = json_encode($level);
            $orderModel->subsidy_money = $level["subsidy"];
            $orderModel->residue_money = $level["subsidy"];
            $orderModel->daily_money = $daily_money;
            $orderModel->goods_id = $level["goods_id"]??0;
            $orderModel->agent_id =$agent_id;
            $orderModel->money = $level["price"]??0;
            //体验卡 id=1
            if($level["id"]==1)
            {
                $orderModel->state='2';
                //计算现金补贴最后一天 start
                $config = get_addon_config('wanlshop');
                $radio_use_day = $config["subsidy"]["radio_use_day"] ?? 10;//有效期天数
                $end_day = ceil($orderModel["subsidy_money"] / $orderModel["daily_money"]);
                $date = strtotime('+' . ($radio_use_day + $end_day + 1) . ' day', time());
                $orderModel->paymenttime=time();
                $orderModel->end_granttime=$date;
                $level_time=strtotime("+ ".($level["duration"]+1)."days",time());
                $user->save(["level_time"=>$level_time,"level_id"=>1]);
                //计算现金补贴最后一天 end
            }
            // 数据库事务操作
            Db::startTrans();
            try {
                if ($orderModel->save()) {

                } else {
                    throw new Exception('网络繁忙，创建订单失败！');
                }
                if($level["id"]!=1)
                {
                    $payList[] = [
                        'user_id' => $this->auth->id,
                        'shop_id' => $goods["shop_id"] ?? 0,
                        'order_id' => $orderModel->id,
                        'order_no' => $orderModel->order_no,
                        'pay_no' => $orderModel->order_no,
                        'price' => $level["price"] <= 0 ? 0.01 : $level["price"],  // 支付价格，系统要求至少支付一分钱
                        'order_price' => $level["price"], // 订单总金额
                        'coupon_price' => 0,  // 优惠券金额
                        'freight_price' => 0, // 快递费
                        'discount_price' => 0, // 优惠金额
                        'number' => 1,
                        'type' => "userlevel"
                    ];
                    $result = model('app\api\model\wanlshop\Pay')->saveAll($payList);
                }
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if($level["id"]==1){
                $this->success('成功');
            }else{
                if ($result !== false) {
                    $this->success('返回成功', ['list' => $result, 'token' => Common::creatToken('orderToken_' . $this->auth->id)]);
                } else {
                    $this->error(__('订单异常，请返回重新下单'));
                }
            }
        } else {
            $this->error(__('非法请求'));
        }
        ///* $goodsModel=new Goods();
        //                 $goods=$goodsModel->get($level["goods_id"]);
        //                 // 生成支付
        //                 $payList[] = [
        //                     'user_id' => $this->auth->id,
        //                     'shop_id' => $goods["shop_id"]??0,
        //                     'order_id'  => $order->id,
        //                     'order_no'  => $order->order_no,
        //                     'pay_no' => $order->order_no,
        //                     'price'  => $level["price"] <= 0 ? 0.01 : $level["price"],  // 支付价格，系统要求至少支付一分钱
        //                     'order_price' => $level["price"], // 订单总金额
        //                     'coupon_price' => 0,  // 优惠券金额
        //                     'freight_price' => 0, // 快递费
        //                     'discount_price' => 0, // 优惠金额
        //                     'number'  => 1,
        //                     'type'  => "userlevel"
        //                 ];
        //                 $result = model('app\api\model\wanlshop\Pay')->saveAll($payList);
        //                 if(!empty($goods)){
        //                     $sku = model('app\api\model\wanlshop\GoodsSku')->where(["goods_id"=>$goods['id']])->find();
        //                     //生成会员等级订单商品记录
        //                     $orderGoodsData=[
        //                         'order_id' =>$order["id"],
        //                         'goods_id' =>$level["goods_id"],
        //                         'title' =>$goods["title"],
        //                         'image' =>$goods["image"],
        //                         'goods_sku_sn' =>$sku["id"]??0,
        //                         'price' =>$goods["price"],
        //                     ];
        //                     model('app\api\model\user\OrderGoods')->save($orderGoodsData);
        //                 }*/
    }

    /**
     *
     * 设置常驻地址
     * */
    public function permanent()
    {
        if ($this->request->isPost()) {
            //设置过滤方法
            $user = $this->auth->getUser();
            if (!empty($user["permanent"])) $this->error(__('您已经设置过常驻地址'));
            $this->request->filter(['strip_tags']);
            $request = $this->request->post();
            $address = new \app\api\model\wanlshop\Address();
            $data = $request['data'];
            /*$data = [
                "adcode" => "120104",
                "address" => "111",
                "address_full" => "111医药馆宜宾道与温江路交叉口东120米",
                //"address_name" => "111医药馆",
                "city" => "天津市",
                "citycode" => "022",
                "country" => "中国",
                "default" => 0,
                "district" => "和平区",
                "formatted_address" => "天津市和平区",
                "location" => "117.129832,39.127549",
                "mobile" => "12111212112",
                "name" => "11",
                "province" => "天津市",
            ];*/
            $request_data = [
                ['address_full', 'require', '地址不能为空'],
                ['city', 'require', '城市不能为空'],
                ['district', 'require', '城市不能为空'],
                ['province', 'require', '城市不能为空'],
                ['mobile', 'require|regex:/^1\d{10}$/', '手机号码不能为空|手机号码格式错误'],
                ['name', 'require', '姓名不能为空'],
            ];
            $validate = new \think\Validate($request_data);
            if (!$validate->check($data)) {
                $this->error('提交失败：' . $validate->getError());
            }
            $data['user_id'] = $this->auth->id;
            $data['permanent'] = 1;
            $count = $address->where(['user_id' => $data['user_id']])->count();
            // 操作

            // 数据库事务操作
            Db::startTrans();
            try {
                if ($count == 0) {
                    // 新增
                    $data['default'] = 1;
                    $address->data($data);
                    $address->allowField(true)->save(); // 1.1.5升级
                } else {
                    $address->data($data);
                    $address->allowField(true)->save(); // 1.1.5升级
                    if ($data['default'] == 1) {
                        $list = \app\api\model\wanlshop\Address::all(['user_id' => $data['user_id']]);
                        $list = collection($list)->toArray();
                        $itemdata = [];
                        foreach ($list as $item) {
                            if ($item['id'] == $address->id) {
                                $item['default'] = 1;
                            } else {
                                $item['default'] = 0;
                            }
                            $itemdata[] = $item;
                        }
                        $address->saveAll($itemdata);
                    }
                }
                $user->permanent = json_encode($data);
                $user->save();
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count == 0) {
                $this->success('地址回调', $address);
            } else {
                $this->success('新增成功', []);
            }
        } else {
            $this->error(__('非法请求'));
        }
    }

    /**
     * 绑定团长
     * */
    public function bindTeam()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isPost()) {
            $data=[
                ['team_id', 'require', '团长id不能为空'],
                ['name', 'require', '姓名为空'],
                ['mobile', 'require|regex:/^1\d{10}$/', '手机号码不能为空|手机号码格式错误'],
            ];
            $validate = new \think\Validate($data);
            if (!$validate->check(input())) {
                $this->error('提交失败：' . $validate->getError());
            }
            $params = $this->request->param();
            $user = $this->auth->getUser();
            if ($user["identity"] == 1) $this->error("您已经是团长");
            if (!empty($user["team_id"]) && $user["is_staff"] == 1) $this->error("您已经绑定团长了！");
            $team_id =$params["team_id"];
            $team = model('app\common\model\User')->find($team_id);
            if (empty($team) || $team["identity"] != 1) $this->error("团长不存在");
            \app\common\model\StaffLog::create([
                "user_id"=>$this->auth->id,
                "team_id"=>$params["team_id"],
                "name"=>$params["name"],
                "mobile"=>$params["mobile"],
                "createtime"=>time(),
            ]);
            $this->success('ok');
        }
        $this->error(__('非法请求'));

    }

    /**
     * 团长员工列表
     * */
    public function staffList()
    {
        if ($this->request->isGet()) {
            $user = $this->auth->getUser();
            if ($user["identity"] != 1) $this->error("您不是团长");
            $list = model('app\common\model\User')
                ->field("id,nickname,avatar,name,staff_mobile")
                ->where(["team_id"=>$this->auth->id,"is_staff"=>1])
                ->paginate();
            $this->success('ok',$list);
        }
        $this->error(__('非法请求'));

    }
    /**
     * 团长查看员工下的用户列表
     * */
    public function userList()
    {
        if(!$this->request->get("user_id")) $this->error("请选择团员");
        if ($this->request->isGet()) {
            $user = $this->auth->getUser();
            if ($user["identity"] != 1) $this->error("您不是团长");
            $list = model('app\common\model\User')
                ->field("id,nickname,avatar,level_id")
                ->where(['agent_id'=>$this->request->get("user_id"),"team_id"=>$user["id"]])
                ->paginate();
            $this->success('ok',$list);
        }
        $this->error(__('非法请求'));
    }
    /**
     * 团长员工申请列表
     * */
    public function staffExamineList()
    {
        if ($this->request->isGet()) {
            $user = $this->auth->getUser();
            if ($user["identity"] != 1) $this->error("您不是团长");
            $list = \app\common\model\StaffLog::
                field("id,staff_log.createtime,staff_log.status,remark,staff_log.name,staff_log.mobile,from_unixtime(staff_log.createtime, '%Y-%m-%d') createtime_text")
                ->with(["user"=>function($query){
                    $query->withField('id,nickname,avatar');
                }])
                ->where(["staff_log.team_id"=>$this->auth->id])
                ->order("staff_log.createtime","desc")
                ->paginate();
            $this->success('ok',$list);
        }
        $this->error(__('非法请求'));

    }

    /**
     * 审核员工申请
     * */
    public function staffExamine()
    {
        if ($this->request->isGet()) {
            $user = $this->auth->getUser();
            if (!$this->request->get("id")) $this->error("员工申请记录id为空");
            if ($user["identity"] != 1) $this->error("您不是团长");
            $model=new \app\common\model\StaffLog();
            $list = $model->where(["team_id"=>$this->auth->id,"id"=>$this->request->get("id")])->find();
            if(empty($list)) $this->error("申请记录不存在");
            if(!empty($list["status"])) $this->error("申请记录已审核");
            $post=$this->request->get();
            if($post["status"]==1){
                $staff=\app\common\model\User::get($list["user_id"]);
                if(!empty($staff["level_id"]) || !empty($staff["level_time"])){
                    $this->error("该用户已购买会员卡,不能审核通过此申请");
                }
            }
            Db::startTrans();
            try {
                if($post["status"]==1){
                    model('app\common\model\User')->where([
                        "id"=>$list["user_id"]])
                        ->update([
                            "is_staff"=>1,
                            "identity"=>3,
                            "team_id"=>$list["team_id"],
                            "name"=>$list["name"],
                            "staff_mobile"=>$list["mobile"],
                        ]);
                    //修改员工下级团长id
                    model('app\common\model\User')->where([
                        "agent_id"=>$list["user_id"]])
                        ->update([
                            "team_id"=>$list["team_id"],
                        ]);
                }
                $post["updatetime"]=time();
                $result = $list->allowField(true)->save($post);
                Db::commit();
            } catch (ValidateException|PDOException|\Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result === false) {
                $this->error("失败");
            }
            $this->success('审核成功');
        }
        $this->error(__('非法请求'));
    }
    /**
     * 会员等级购买记录
     * */
    public function levelLog()
    {
        if ($this->request->isPost()) {
            $user = $this->auth->getUser();
            if (!$this->request->get("id")) $this->error("员工申请记录id为空");
            if ($user["identity"] != 1) $this->error("您不是团长");
            $model=new \app\common\model\LevelOrder();
            $list = $model->where(["team_id"=>$this->auth->id,"user_id"=>$this->request->get("id")])->select();
            $this->success('审核成功',$list);
        }
        $this->error(__('非法请求'));
    }
    /**
     * 补贴现金
     * */
    public function perkList()
    {
        $list=Perk::field("id,money,from_unixtime(createtime, '%Y-%m-%d') createtime,type")
            ->where(["user_id"=>$this->auth->id])
            ->order("createtime","desc")
            ->paginate();
        $this->success('成功',$list);
    }
    /**
     * 会员卡购买记录
     * */
    public function levelPayLog()
    {
        $list=LevelOrder::field("id,level_details,order_no,createtime")
            ->where(["user_id"=>$this->auth->id,"state"=>2])->select();
        if(!empty($list)){
            foreach ($list as &$v){
                $level_details=json_decode($v["level_details"],true);
                $v["level_details"]=[
                    "name"=>$level_details["name"],
                    "price"=>$level_details["price"],
                ];
            }
        }
        $this->success('成功',$list);
    }
    /**
     * 现金补贴使用记录
     * */
    public function perkMoneyLog()
    {
        $list=PerkLog::field("id,perk_money,order_no,createtime,from_unixtime(createtime, '%Y-%m-%d') createtime_text")
            ->where(["user_id"=>$this->auth->id])
            ->order("createtime","desc")
            ->paginate();
        $this->success('成功',$list);
    }

    //2024-2-2 新增 start
    /**
     * 扫码记录
     * */
    public function scanLog()
    {
        if ($this->request->isGet()) {
            if (!$this->request->get("user_id")) $this->error("用户id为空");
            $model=new ScanLog();
            $model->save([
                "user_id"=>$this->auth->id,
                "click_id"=>$this->request->get("user_id"),
            ]);
            $this->success('成功');
        }
        $this->error(__('非法请求'));
    }
    //2024-2-2 新增 end
    //新增 lina end
}